package com.example.demo.controller;

import com.example.demo.bean.User;
import com.example.demo.common.Result;
import com.example.demo.service.UserService;

import com.example.demo.jwt.ResultCode;
import com.example.demo.common.PageResult;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Collections;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("/api/user")
public class UserController {
    
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    
    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/test")
    public Result<String> test() {
        log.info("测试接口被调用");
        return Result.success("测试接口正常");
    }

    @GetMapping("/current")
    public Result<User> getCurrentUser() {
        log.info("获取当前用户信息接口被调用");
        try {
            User user = userService.getCurrentUser();
            log.info("获取到用户信息: {}", user);
            return Result.success(user);
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            return Result.error(ResultCode.ERROR.getCode(), "获取用户信息失败：" + e.getMessage());
        }
    }

    @GetMapping("/all")
    @PreAuthorize("hasAuthority('ADMIN')")
    public Result<List<User>> getAllUsers() {
        try {
            List<User> users = userService.getAllUsers();
            return Result.success(users);
        } catch (Exception e) {
            log.error("获取用户列表失败", e);
            return Result.error(ResultCode.ERROR.getCode(), "获取用户列表失败：" + e.getMessage());
        }
    }

    @PutMapping("/update")
    @PreAuthorize("hasAnyAuthority('ADMIN', 'USER')")
    public Result<User> updateUser(@RequestBody User user) {
        try {
            User updatedUser = userService.updateUser(user);
            return Result.success(updatedUser);
        } catch (Exception e) {
            log.error("更新用户信息失败", e);
            return Result.error(ResultCode.ERROR.getCode(), "更新用户信息失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> deleteUser(@PathVariable Integer id) {
        try {
            userService.deleteUser(id);
            return Result.success(null);
        } catch (Exception e) {
            log.error("删除用户失败", e);
            return Result.error(ResultCode.ERROR.getCode(), "删除用户失败：" + e.getMessage());
        }
    }

    @GetMapping("/class/{className}")
    public Result<List<User>> getUsersByClass(@PathVariable String className) {
        try {
            List<User> users = userService.getUsersByClass(className);
            return Result.success(users);
        } catch (Exception e) {
            log.error("查询班级用户失败", e);
            return Result.error(ResultCode.ERROR.getCode(), "查询班级用户失败：" + e.getMessage());
        }
    }

    @GetMapping("/page")
    @PreAuthorize("isAuthenticated()")
    public Result<PageResult<User>> getUsersByPage(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String search) {
        try {
            log.debug("接收到分页请求参数: pageNum={}, pageSize={}, search={}", pageNum, pageSize, search);
            PageResult<User> pageResult = userService.getUsersByPage(pageNum, pageSize, search);
            if (pageResult == null || pageResult.getRecords() == null || pageResult.getRecords().isEmpty()) {
                log.debug("查询结果为空");
                return Result.success(new PageResult<>(Collections.emptyList(), 0L, pageNum, pageSize));
            }
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("分页查询用户失败: {}", e.getMessage(), e);
            return Result.error(ResultCode.ERROR.getCode(), "分页查询用户失败");
        }
    }
}